package main

import (
	"encoding/json"
	"flag"
	"github.com/go-chi/chi/v5"
	"net/http"
	"net/http/httputil"
)

type option struct {
	Addr string
}

var opt option

func returnJson(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if data != nil {
		json.NewEncoder(w).Encode(data)
	}
}

type qychat struct {
}

type qyResponse struct {
	ErrCode int    `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

func (q *qychat) initRouter(router chi.Router) {
	router.Get("/gettoken", func(w http.ResponseWriter, r *http.Request) {
		returnJson(w, nil)
		w.Write([]byte("{\"errcode\":0,\"errmsg\":\"ok\",\"access_token\":\"accesstoken000001\",\"expires_in\":7200}"))
	})
	router.Route("/agent", func(c chi.Router) {
		c.Get("/get", func(w http.ResponseWriter, req *http.Request) {
			returnJson(w, nil)
			var agentInfo = `{
   "errcode": 0,
   "errmsg": "ok",
   "allow_partys": {
       "partyid": [1]
    }
}
`
			w.Write([]byte(agentInfo))
		})
	})
	router.Route("/user", q.user)
	router.Route("/message", q.message)
	router.NotFound(q.notFound)
}

func (q *qychat) user(router chi.Router) {
	router.Get("/simplelist", q.simplelist)
}

func (q *qychat) notFound(w http.ResponseWriter, r *http.Request) {
	rs := &qyResponse{
		ErrCode: 9000,
		ErrMsg:  r.URL.Path + "?" + r.URL.RawQuery,
	}
	returnJson(w, rs)
}

func (q *qychat) simplelist(w http.ResponseWriter, r *http.Request) {
	userList := `{
   "errcode": 0,
   "errmsg": "ok",
   "userlist": [
           {
                  "userid": "01407586",
                  "name": "杨少峰"
           }
     ]
}
`
	returnJson(w, nil)
	w.Write([]byte(userList))
}

func (q *qychat) message(router chi.Router) {
	router.Post("/send", func(w http.ResponseWriter, r *http.Request) {

	})

}

func initRouter() chi.Router {
	r := chi.NewRouter()
	q := new(qychat)
	r.Route("/qychat/cgi-bin/", q.initRouter)
	return r
}

func main() {
	router := initRouter()
	flag.StringVar(&opt.Addr, "l", ":8081", "http server addr")
	flag.Parse()
	println("start server ar", opt.Addr)
	err := http.ListenAndServe(opt.Addr, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		body, err := httputil.DumpRequest(r, true)
		if err == nil {
			println("=================req==================")
			println(string(body))
		} else {
			println("request err", err.Error())
		}
		router.ServeHTTP(w, r)
	}))

	if err != nil {
		println(err.Error())
	}

}
